//
//  DownloadTaskViewController.m
//  NSURLSessionStudyDemo
//
//  Created by zzp on 2018/5/6.
//  Copyright © 2018年 内蒙小猿. All rights reserved.
//

#import "DownloadTaskViewController.h"

@interface DownloadTaskViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *downLoadTaskImageView;

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@end

@implementation DownloadTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)beginButtonClick:(id)sender {
    self.statusLabel.text = @"正在下载";
    //1.创建session
    NSURLSession *session = [NSURLSession sharedSession];
    //2.创建task
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_03.png"];
    /*
     location:文件的临时保存路径
     注意:它内部已经完成了边下载边写入数据的操作
     block 回调不是主线程的
     */
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",location);
        
        //确定文件要存放到哪里
        //caches
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *fullPath = [caches stringByAppendingPathComponent:response.suggestedFilename];
        
        
        //剪切文件到目的地
        NSFileManager *manager = [NSFileManager defaultManager];
        
        [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.statusLabel.text = @"下载完成";
            self.downLoadTaskImageView.image = [UIImage imageWithContentsOfFile:fullPath];
        });
        NSLog(@"%@",fullPath);
    }];
    //3.启动
    [downloadTask resume];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
